package com.paw.wechat;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.validation.constraints.NotBlank;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.bean.WxMaJscode2SessionResult;
import cn.binarywang.wx.miniapp.bean.WxMaPhoneNumberInfo;
import cn.binarywang.wx.miniapp.bean.WxMaSubscribeMessage;
import cn.binarywang.wx.miniapp.bean.WxMaSubscribeMessage.MsgData;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.error.WxErrorException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author lvzihai
 * @date 2022/10/15
 **/
@Slf4j
@RestController
@RequestMapping("/api/wxMiniApp")
public class WxMiniAppController {


  @Autowired
  private WxMaService wxMaService;

  @ApiOperation("获取微信授权信息")
  @ApiImplicitParam(name = "code",value = "前端授权登录后传来的code", required = true,paramType = "query")
  @RequestMapping(value = "/wechatSession", method = RequestMethod.POST)
  @ResponseBody
  public Object wechatSession(@RequestParam String code) throws WxErrorException {
    //获取openId、unionid、session_key
    WxMaJscode2SessionResult sessionInfo = wxMaService.getUserService().getSessionInfo(code);
    return sessionInfo;
  }


  @ApiOperation("小程序手机号登录")
  @ApiImplicitParams({
      @ApiImplicitParam(name = "sessionKey", value = "sessionKey", paramType = "query", dataType = "string", required = true),
      @ApiImplicitParam(name = "encryptedData", value = "加密串", paramType = "query", dataType = "string", required = true),
      @ApiImplicitParam(name = "iv", value = "偏移量", paramType = "query", dataType = "string", required = true)
  })
  @RequestMapping(value = "/wechatLogin", method = RequestMethod.POST)
  @ResponseBody
  public Object wechatLogin(HttpServletRequest request,
      @RequestParam @NotBlank(message = "sessionKey不能为空") String sessionKey,
      @RequestParam @NotBlank(message = "加密串不能为空") String encryptedData,
      @RequestParam @NotBlank(message = "偏移串不能为空") String iv) {
    WxMaPhoneNumberInfo phoneInfo = wxMaService.getUserService().getPhoneNoInfo(sessionKey, encryptedData, iv);
    return phoneInfo.getPurePhoneNumber();
  }



  @Value("${wx.miniapp.msg.template_id_1:''}")
  private String msgTemplateId1;

  @Value("${wx.miniapp.msg.template_id_2:''}")
  private String msgTemplateId2;

  /**
   openId : 用户微信登录的openID
   */
  private boolean sendSubscribeMessage(String openId) {
    // 应该是消息点击后跳转页面
    String page="pages/index/index";
    WxMaSubscribeMessage message = new WxMaSubscribeMessage();
    message.setTemplateId(msgTemplateId1);
    message.setToUser(openId);
    message.setPage(page);
    List<MsgData> subscribeDataList = new ArrayList<>();
    WxMaSubscribeMessage.MsgData subscribeData = new WxMaSubscribeMessage.MsgData();
    // 你在小程序自定义的key(比如“商家名称”)
    subscribeData.setName("key1");
    //key对应的内容
    subscribeData.setValue("奈雪的茶");
    //添加你配置要且要展示的内容
    subscribeDataList.add(subscribeData);

    message.setData(subscribeDataList);
    try {
      wxMaService.getMsgService().sendSubscribeMsg(message);
      return true;
    } catch (WxErrorException e) {
      log.error("发送小程序订阅消息失败，errCode:{}，errMsg:{}", e.getError().getErrorCode(), e.getError().getErrorMsg());
    }
    return false;
  }




}
